package com.imut.lagain.controller;

import com.imut.lagain.service.IPeriodPredictionService;
import com.imut.lagain.service.IHealthReminderService;
import com.imut.lagain.service.IPeriodCareService;
import com.imut.lagain.service.IPeriodReportService;
import com.imut.lagain.util.JwtUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.Valid;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生理期健康控制器
 */
@RestController
@RequestMapping("/api/period-health")
@RequiredArgsConstructor
@Validated
public class PeriodHealthController {
    private static final Logger log = LoggerFactory.getLogger(PeriodHealthController.class);

    private final IPeriodPredictionService periodPredictionService;
    private final IHealthReminderService healthReminderService;
    private final IPeriodCareService careService;
    private final IPeriodReportService reportService;
    private final JwtUtil jwtUtil;

    /**
     * 获取生理期预测
     */
    @GetMapping("/predictions")
    public ResponseEntity<Map<String, Object>> getPredictions(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Map<String, Object> predictions = periodPredictionService.getPredictions(userId);
            response.put("success", true);
            response.put("data", predictions);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取生理期预测失败", e);
            response.put("success", false);
            response.put("message", "获取生理期预测失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取未来周期预测
     */
    @GetMapping("/future-cycles")
    public ResponseEntity<Map<String, Object>> getFutureCycles(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "6") int cycles) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<Map<String, Object>> futureCycles = periodPredictionService.getFutureCycles(userId, cycles);
            response.put("success", true);
            response.put("data", futureCycles);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取未来周期预测失败", e);
            response.put("success", false);
            response.put("message", "获取未来周期预测失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取健康建议
     */
    @PostMapping("/health-tips")
    public ResponseEntity<Map<String, Object>> getHealthTips(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody HealthTipsRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<Map<String, Object>> tips = healthReminderService.getHealthTips(userId, request.getCurrentPhase());
            response.put("success", true);
            response.put("data", tips);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取健康建议失败", e);
            response.put("success", false);
            response.put("message", "获取健康建议失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取症状分析
     */
    @GetMapping("/symptom-analysis")
    public ResponseEntity<Map<String, Object>> getSymptomAnalysis(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Map<String, Object> analysis = healthReminderService.getSymptomAnalysis(userId);
            response.put("success", true);
            response.put("data", analysis);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取症状分析失败", e);
            response.put("success", false);
            response.put("message", "获取症状分析失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取周期异常
     */
    @GetMapping("/cycle-anomalies")
    public ResponseEntity<Map<String, Object>> getCycleAnomalies(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<Map<String, Object>> anomalies = periodPredictionService.getCycleAnomalies(userId);
            response.put("success", true);
            response.put("data", anomalies);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取周期异常失败", e);
            response.put("success", false);
            response.put("message", "获取周期异常失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取周期统计
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getCycleStatistics(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Map<String, Object> statistics = periodPredictionService.getCycleStatistics(userId);
            response.put("success", true);
            response.put("data", statistics);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取周期统计失败", e);
            response.put("success", false);
            response.put("message", "获取周期统计失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取当前阶段
     */
    @GetMapping("/current-phase")
    public ResponseEntity<Map<String, Object>> getCurrentPhase(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Map<String, Object> currentPhase = periodPredictionService.getCurrentPhase(userId);
            response.put("success", true);
            response.put("data", currentPhase);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取当前阶段失败", e);
            response.put("success", false);
            response.put("message", "获取当前阶段失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取提醒统计
     */
    @GetMapping("/reminder-stats")
    public ResponseEntity<Map<String, Object>> getReminderStats(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Map<String, Object> stats = healthReminderService.getReminderStatistics(userId);
            response.put("success", true);
            response.put("data", stats);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取提醒统计失败", e);
            response.put("success", false);
            response.put("message", "获取提醒统计失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取关怀建议
     */
    @GetMapping("/care-recommendations")
    public ResponseEntity<Map<String, Object>> getCareRecommendations(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam String currentPhase) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<Map<String, String>> recommendations = careService.getCareRecommendations(userId, currentPhase);
            response.put("success", true);
            response.put("data", recommendations);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取关怀建议失败", e);
            response.put("success", false);
            response.put("message", "获取关怀建议失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 发送关怀消息
     */
    @PostMapping("/care-message")
    public ResponseEntity<Map<String, Object>> sendCareMessage(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody CareMessageRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = careService.sendCareMessage(userId, request.getToUserId(), 
                    request.getCareType(), request.getMessage());
            response.put("success", success);
            response.put("message", success ? "关怀消息发送成功" : "关怀消息发送失败");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("发送关怀消息失败", e);
            response.put("success", false);
            response.put("message", "发送关怀消息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 健康建议请求类
     */
    @Data
    public static class HealthTipsRequest {
        @NotBlank(message = "当前阶段不能为空")
        private String currentPhase;

        public String getCurrentPhase() {
            return currentPhase;
        }
    }

    /**
     * 关怀消息请求类
     */
    @Data
    public static class CareMessageRequest {
        @NotNull(message = "接收用户ID不能为空")
        private Long toUserId;

        @NotBlank(message = "关怀类型不能为空")
        private String careType;

        @NotBlank(message = "消息内容不能为空")
        private String message;

        public Long getToUserId() {
            return toUserId;
        }

        public String getCareType() {
            return careType;
        }

        public String getMessage() {
            return message;
        }
    }
}